package com.fly.estore.controller;

import com.fly.estore.constant.AccountConstant;
import com.fly.estore.domain.AccountInfo;
import com.fly.estore.framework.common.AjaxResult;
import com.fly.estore.framework.session.AccountSession;
import com.fly.estore.framework.session.SessionManager;
import com.fly.estore.framework.session.support.SessionInfo;
import com.fly.estore.framework.util.CommonUtil;
import com.fly.estore.framework.util.CookieUtil;
import com.fly.estore.service.AccountService;
import com.fly.estore.service.MemberService;
import com.fly.estore.service.ProductService;
import com.fly.estore.service.SaleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Fly on 2016/3/25.
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountService accountService;
    @Autowired
    SessionManager sessionManager;
    @Autowired
    MemberService memberService;
    @Autowired
    SaleService saleService;
    @Autowired
    ProductService productService;

    @RequestMapping("/add")
    @ResponseBody
    public String AccountAdd(){
        AccountInfo accountInfo = new AccountInfo();
        accountInfo.setAccountId(CommonUtil.genPK());
        accountInfo.setAccountName("管理员");
        accountInfo.setPassword(CommonUtil.MD5Encode("123456"));
        accountInfo.setAccountStatus(AccountConstant.ACCOUNT_STATUS_ENABLE);
        accountInfo.setCreateTime(CommonUtil.dateToStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
        int update = accountService.create(accountInfo);
        if (update > 0){
            return "success";
        }
        else{
            return "failed";
        }
    }

    @RequestMapping("/to-login")
    public String toLogin(){
        return "/login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Map login(
            @RequestParam("account_name")String accountName,
            @RequestParam("password")String password,
            HttpServletRequest request,
            HttpServletResponse response
    ){
        Map map = new HashMap();
        map.put("status", "error");
        AccountInfo accountInfo = accountService.getByAccountNameAndPwd(accountName, password);
        if (null != accountInfo){
            //账号存在
            if (accountInfo.getAccountStatus().equals(AccountConstant.ACCOUNT_STATUS_ENABLE)){

                String sessionId = sessionManager.createAccountSession(request, accountInfo);
                CookieUtil.writeCookie(response, CookieUtil.ACCOUNT_COOKIE, sessionId);

                map.put("status", "success");
                map.put("result", request.getContextPath() + "/account/index");
            }
            else{
                map.put("result", "账号状态异常");
            }
        }
        else{
            //账号不存在
            map.put("result", "登录失败，账号名或密码错误！");
        }
        return map;
    }

    @RequestMapping("/logout")
    public String logout(
            HttpServletRequest request
    ){
        String sessionId = CookieUtil.readCookie(request, CookieUtil.ACCOUNT_COOKIE);
        sessionManager.removeAccountSession(request, sessionId);
        return "redirect:/account/index";
    }

    @RequestMapping("/index")
    public String toIndex(
            @SessionInfo AccountSession session,
            ModelMap model
    ){
//        System.out.println(session.getAccountId());
        model.addAttribute("memberCount", memberService.getMemberCount(""));
        model.addAttribute("memberTodayCount", memberService.getMemberCount(CommonUtil.dateToStr(new Date(), "yyyy-MM-dd")));
        model.addAttribute("salePrice", saleService.getSalePrice(CommonUtil.firstDateInWeek(new Date())));
        model.addAttribute("saleTodayPrice", saleService.getSalePrice(CommonUtil.dateToStr(new Date(), "yyyy-MM-dd")));
        model.addAttribute("productCount", productService.getProductCount());
        model.addAttribute("account", session);
        return "index";
    }

    @RequestMapping("/to-demo")
    public String toDemo(){
        return "demo";
    }

    @RequestMapping("/to-changePassword")
    public String toChangePassword(){
        return "/account/changePassword";
    }

    @RequestMapping("/changePassword")
    @ResponseBody
    public AjaxResult changePassword(
            @RequestParam("new_password")String newPassword,
            @RequestParam("old_password")String oldPassword,
            @RequestParam("confirm_password")String confirmPassword,
            @SessionInfo AccountSession accountSession
    ){
        String message = "";
        int update = 0;
        if (!newPassword.equals(confirmPassword)){
            message = "两次输入密码不一致！";
        }
        else{
            update = accountService.changePassword(oldPassword, newPassword, accountSession.getAccountId());
        }
        AjaxResult result = new AjaxResult();
        result.setStatus(update > 0 ? AjaxResult.STATUS_SUCCESS : AjaxResult.STATUS_ERROR);
        return result;
    }

    @RequestMapping("/account/list")
    public String accountList(
            ModelMap model
    ){
        List<AccountInfo> accountList = accountService.getList();
        model.addAttribute("accountList", accountList);
        return "/account/list";
    }

    @RequestMapping("/account/detail")
    public String accountDetail(
            @RequestParam(value = "accountId", required = false, defaultValue = "")String accountId,
            ModelMap model
    ){
        AccountInfo accountInfo = new AccountInfo();
        if (StringUtils.isNotBlank(accountId)){
            accountInfo = accountService.getById(accountId);
        }
        model.addAttribute("account", accountInfo);
        return "/account/detail";
    }

    @RequestMapping("/account/save")
    public AjaxResult saveAccount(
            @RequestParam(value = "accountId", required = false, defaultValue = "")String accountId,
            @RequestParam(value = "accountName", required = false, defaultValue = "")String accountName,
            @RequestParam(value = "mobile", required = false, defaultValue = "")String mobile,
            @SessionInfo AccountSession accountSession
    ){
        AccountInfo account = new AccountInfo();
        account.setAccountId(accountId);
        account.setAccountName(accountName);
        account.setMobile(mobile);
        account.setCreateId(accountSession.getAccountId());
        account.setCreateTime(CommonUtil.currentTime());
        account.setLastUpdateId(accountSession.getAccountId());
        account.setLastUpdateTime(CommonUtil.currentTime());
        int update = accountService.save(account);
        AjaxResult result = new AjaxResult();
        result.setStatus(update > 0 ? AjaxResult.STATUS_SUCCESS : AjaxResult.STATUS_ERROR);
        return result;
    }
}
